package com.thread.blogsthreadparties4000.service.impl;

import com.mucd.blog.result.R;
import com.mucd.blog.result.Result;
import com.mucd.blog.statuscode.MyException;
import com.mucd.blog.statuscode.StatusCode;
import com.thread.blogsthreadparties4000.service.PictureService;
import com.thread.blogsthreadparties4000.util.QiniuUtils;
import com.thread.blogsthreadparties4000.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;

@Service
public class PictureServiceImpl implements PictureService {

    @Autowired
    private QiniuUtils qiniuUtils;

    @Override
    public Result<String> upload(MultipartFile file) {
        if (file.isEmpty()) {
            return Result.buildFailMsg(HttpStatus.ACCEPTED.value(), "上传文件为空,请重试...");
        }
        String fileName = StringUtils.getRandomImgName(Objects.requireNonNull(file.getOriginalFilename()));
        try {
            FileInputStream uploadFile = (FileInputStream) file.getInputStream();
            String path = qiniuUtils.upload(uploadFile, fileName);
            return Result.buildSuccessData("上传成功...", path);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.buildFailMsg(HttpStatus.INTERNAL_SERVER_ERROR.value(), "服务器内部错误...");
        }
    }

    @Override
    public R uploadHead(MultipartFile file) {
        if (file.isEmpty()) {
            return R.error("上传文件为空,请重试...");
        }
        String fileName = StringUtils.getRandomImgName(Objects.requireNonNull(file.getOriginalFilename()));
        try {
            FileInputStream uploadFile = (FileInputStream) file.getInputStream();
            String path = qiniuUtils.upload(uploadFile, fileName);
            return R.ok(path);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException(StatusCode.EXCEPTION_ERROR);
        }
    }

}